﻿Imports System.Net
Imports System.Net.Sockets

Friend Class Listener
    Private Shared mListenThread As Threading.Thread
    Private Shared mListener As TcpListener


    Public ReadOnly Property CurrentPort() As Integer
        Get
            Return CType(mListener.LocalEndpoint, IPEndPoint).Port
        End Get
    End Property

    Public Sub Start()
        mListener = New TcpListener(IPAddress.Any, Settings.Port)
        mListener.Start()

        mListenThread = New Threading.Thread(AddressOf Listener)
        mListenThread.Name = "TCP Listening Thread"
        mListenThread.IsBackground = True
        mListenThread.Start()
    End Sub
    Public Sub [Stop]()
        mListenThread.Abort()
        mListener.Stop()
    End Sub

    Private Shared Sub Listener()
        Try
            While True
                Try
                    Dim clsNewClient As TcpClient = mListener.AcceptTcpClient()
                    Dim clsClient As New Client
                    Manager.AddClient(clsClient)

                    clsClient.StartServer(clsNewClient)
                Catch ex As Threading.ThreadAbortException
                    Exit While
                Catch ex As Exception
                End Try
            End While
        Catch ex As Threading.ThreadAbortException
        Catch ex As Exception
        End Try
    End Sub

End Class
